/**
 * 超深度上下文学习脚本 - Foundation 专项版
 * 
 * 专注于学习 OHCode/foundation 目录下的所有项目
 * 包括：
 * - ability (8个项目)
 * - ai (3个项目)
 * - arkui (7个项目)
 * - barrierfree (1个项目)
 * - bundlemanager (7个项目)
 * - CastEngine (2个项目)
 * - communication (18个项目)
 * - deviceprofile (1个项目)
 * - distributeddatamgr (9个项目)
 * - distributedhardware (7个项目)
 * - filemanagement (6个项目)
 * - graphic (7个项目)
 * - multimedia (18个项目)
 * - multimodalinput (1个项目)
 * - resourceschedule (8个项目)
 * - systemabilitymgr (4个项目)
 * - window (3个项目)
 * 
 * 总计：110个项目
 */

const fs = require('fs');
const path = require('path');

class UltraDeepFoundationLearner {
    constructor() {
        this.ohcodeDir = path.join(__dirname, '../OHCode/foundation');
        this.outputDir = path.join(__dirname, '../core/knowledge');
        this.allProjects = [];
        this.contextGraph = {
            sourceContexts: [],
            testContexts: [],
            fuzzContexts: [],
            mockContexts: [],
            sourceToTestMapping: {},
            sourceToFuzzMapping: {},
            gnRelationships: [],
            stats: {}
        };
    }

    async run() {
        console.log('\n🚀 开始Foundation专项超深度学习...\n');
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
        
        const startTime = Date.now();
        
        // 步骤1：扫描foundation下的所有项目
        console.log('📦 步骤1: 扫描Foundation目录...\n');
        this.allProjects = await this.scanAllProjects();
        console.log(`   ✅ 发现 ${this.allProjects.length} 个项目\n`);
        
        // 步骤2：构建源文件上下文
        console.log('📂 步骤2: 构建源文件上下文...\n');
        await this.buildSourceContexts();
        console.log(`   ✅ 构建了 ${this.contextGraph.sourceContexts.length} 个源文件上下文\n`);
        
        // 步骤3：构建测试文件上下文
        console.log('🧪 步骤3: 构建测试文件上下文...\n');
        await this.buildTestContexts();
        console.log(`   ✅ 构建了 ${this.contextGraph.testContexts.length} 个测试文件上下文\n`);
        
        // 步骤4：构建Fuzz文件上下文
        console.log('🎯 步骤4: 构建Fuzz文件上下文...\n');
        await this.buildFuzzContexts();
        console.log(`   ✅ 构建了 ${this.contextGraph.fuzzContexts.length} 个Fuzz文件上下文\n`);
        
        // 步骤5：构建Mock文件上下文
        console.log('🎭 步骤5: 构建Mock文件上下文...\n');
        await this.buildMockContexts();
        console.log(`   ✅ 构建了 ${this.contextGraph.mockContexts.length} 个Mock文件上下文\n`);
        
        // 步骤6：建立文件映射关系
        console.log('🔗 步骤6: 建立文件映射关系...\n');
        this.establishFileMappings();
        console.log(`   ✅ 建立了 ${Object.keys(this.contextGraph.sourceToTestMapping).length} 个源→测试映射\n`);
        console.log(`   ✅ 建立了 ${Object.keys(this.contextGraph.sourceToFuzzMapping).length} 个源→Fuzz映射\n`);
        
        // 步骤7：分析GN关系
        console.log('📐 步骤7: 分析GN关系图谱...\n');
        this.analyzeGNDependencies();
        console.log(`   ✅ 分析了 ${this.contextGraph.gnRelationships.length} 个GN关系\n`);
        
        // 保存结果
        await this.saveResults();
        
        const endTime = Date.now();
        const duration = ((endTime - startTime) / 1000).toFixed(2);
        
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        console.log(`✅ Foundation专项学习完成！耗时: ${duration} 秒`);
        this.printSummary();
    }

    /**
     * 扫描所有项目（只扫描foundation目录）
     */
    async scanAllProjects() {
        const projects = [];
        
        const scanDir = (dir, depth = 0) => {
            if (depth > 5) return;
            
            try {
                const entries = fs.readdirSync(dir, { withFileTypes: true });
                const hasBundleJson = entries.some(e => e.name === 'bundle.json');
                
                if (hasBundleJson) {
                    projects.push(dir);
                    return;
                }
                
                for (const entry of entries) {
                    if (entry.isDirectory() && !entry.name.startsWith('.') && 
                        entry.name !== 'node_modules' && entry.name !== 'out') {
                        scanDir(path.join(dir, entry.name), depth + 1);
                    }
                }
            } catch (e) {}
        };
        
        scanDir(this.ohcodeDir);
        return projects;
    }

    /**
     * 构建源文件上下文（Foundation重点学习，无限制）
     */
    async buildSourceContexts() {
        let processedCount = 0;
        const maxLimit = 20000; // Foundation专项，大幅提高限制
        
        for (const project of this.allProjects) {
            if (processedCount >= maxLimit) break;
            
            const sourceFiles = this.findSourceFiles(project, ['test', 'tests', 'mock']);
            
            for (const sourceFile of sourceFiles) {
                if (processedCount >= maxLimit) break;
                
                this.contextGraph.sourceContexts.push({
                    file: sourceFile,
                    project: project,
                    relativePath: path.relative(this.ohcodeDir, sourceFile)
                });
                
                processedCount++;
                if (processedCount % 1000 === 0) {
                    console.log(`      已处理 ${processedCount} 个源文件...`);
                }
            }
        }
    }

    /**
     * 构建测试文件上下文（递归扫描所有子模块）
     */
    async buildTestContexts() {
        let processedCount = 0;
        const maxLimit = 50000; // Foundation重点，无限制
        
        console.log('   🔍 递归扫描所有子模块的 test 目录...\n');
        
        for (const project of this.allProjects) {
            if (processedCount >= maxLimit) break;
            
            const projectName = path.basename(project);
            const testDirs = this.findAllTestDirectories(project);
            
            if (testDirs.length > 0) {
                console.log(`      [${projectName}] 发现 ${testDirs.length} 个测试目录`);
            }
            
            for (const testDir of testDirs) {
                const testFiles = this.findTestFiles(testDir);
                
                for (const testFile of testFiles) {
                    if (processedCount >= maxLimit) break;
                    
                    const analysis = this.deepAnalyzeTestFunctions(testFile);
                    
                    this.contextGraph.testContexts.push({
                        testFile: testFile,
                        project: project,
                        ...analysis
                    });
                    
                    processedCount++;
                    if (processedCount % 100 === 0) {
                        console.log(`      已处理 ${processedCount} 个测试文件...`);
                    }
                }
            }
        }
    }

    /**
     * 构建Fuzz文件上下文（递归扫描）
     */
    async buildFuzzContexts() {
        let processedCount = 0;
        const maxLimit = 20000;
        
        console.log('   🔍 递归扫描所有子模块的 fuzz 目录...\n');
        
        for (const project of this.allProjects) {
            if (processedCount >= maxLimit) break;
            
            const projectName = path.basename(project);
            const fuzzDirs = this.findAllFuzzDirectories(project);
            
            if (fuzzDirs.length > 0) {
                console.log(`      [${projectName}] 发现 ${fuzzDirs.length} 个Fuzz目录`);
            }
            
            for (const fuzzDir of fuzzDirs) {
                const fuzzFiles = this.findFuzzFiles(fuzzDir);
                
                for (const fuzzFile of fuzzFiles) {
                    if (processedCount >= maxLimit) break;
                    
                    const analysis = this.deepAnalyzeFuzzerFunctions(fuzzFile);
                    
                    this.contextGraph.fuzzContexts.push({
                        fuzzFile: fuzzFile,
                        project: project,
                        ...analysis
                    });
                    
                    processedCount++;
                    if (processedCount % 100 === 0) {
                        console.log(`      已处理 ${processedCount} 个Fuzz文件...`);
                    }
                }
            }
        }
    }

    /**
     * 构建Mock文件上下文（递归扫描）
     */
    async buildMockContexts() {
        let processedCount = 0;
        const maxLimit = 20000;
        
        console.log('   🔍 递归扫描所有子模块的 mock 目录...\n');
        
        for (const project of this.allProjects) {
            if (processedCount >= maxLimit) break;
            
            const projectName = path.basename(project);
            const mockFiles = this.findAllMockFiles(project);
            
            if (mockFiles.length > 0) {
                console.log(`      [${projectName}] 发现 ${mockFiles.length} 个Mock文件`);
            }
            
            for (const mockFile of mockFiles) {
                if (processedCount >= maxLimit) break;
                
                const analysis = this.deepAnalyzeMockImplementation(mockFile);
                
                this.contextGraph.mockContexts.push({
                    mockFile: mockFile,
                    project: project,
                    ...analysis
                });
                
                processedCount++;
                if (processedCount % 100 === 0) {
                    console.log(`      已处理 ${processedCount} 个Mock文件...`);
                }
            }
        }
    }

    /**
     * 递归查找所有test/unittest目录
     */
    findAllTestDirectories(projectRoot, maxDepth = 10) {
        const testDirs = [];
        
        const scanForTests = (dir, depth = 0) => {
            if (depth > maxDepth) return;
            
            try {
                const entries = fs.readdirSync(dir, { withFileTypes: true });
                
                for (const entry of entries) {
                    if (entry.isDirectory()) {
                        const fullPath = path.join(dir, entry.name);
                        
                        if (entry.name === 'unittest' || entry.name === 'unittests') {
                            testDirs.push(fullPath);
                        } else if (entry.name === 'test' || entry.name === 'tests') {
                            testDirs.push(fullPath);
                            scanForTests(fullPath, depth + 1);
                        } else if (!entry.name.startsWith('.') && entry.name !== 'node_modules') {
                            scanForTests(fullPath, depth + 1);
                        }
                    }
                }
            } catch (e) {}
        };
        
        scanForTests(projectRoot);
        return testDirs;
    }

    /**
     * 递归查找所有fuzz目录
     */
    findAllFuzzDirectories(projectRoot, maxDepth = 10) {
        const fuzzDirs = [];
        
        const scanForFuzz = (dir, depth = 0) => {
            if (depth > maxDepth) return;
            
            try {
                const entries = fs.readdirSync(dir, { withFileTypes: true });
                
                for (const entry of entries) {
                    if (entry.isDirectory()) {
                        const fullPath = path.join(dir, entry.name);
                        
                        if (entry.name === 'fuzztest' || entry.name === 'fuzz') {
                            fuzzDirs.push(fullPath);
                        } else if (!entry.name.startsWith('.') && entry.name !== 'node_modules') {
                            scanForFuzz(fullPath, depth + 1);
                        }
                    }
                }
            } catch (e) {}
        };
        
        scanForFuzz(projectRoot);
        return fuzzDirs;
    }

    /**
     * 递归查找所有mock文件
     */
    findAllMockFiles(projectRoot, maxDepth = 10) {
        const mockFiles = [];
        
        const scanForMocks = (dir, depth = 0) => {
            if (depth > maxDepth) return;
            
            try {
                const entries = fs.readdirSync(dir, { withFileTypes: true });
                
                for (const entry of entries) {
                    const fullPath = path.join(dir, entry.name);
                    
                    if (entry.isFile() && (entry.name === 'mock.h' || entry.name === 'mock.cpp' || 
                        entry.name.includes('_mock.') || entry.name.includes('Mock.'))) {
                        mockFiles.push(fullPath);
                    } else if (entry.isDirectory() && !entry.name.startsWith('.') && 
                              entry.name !== 'node_modules') {
                        scanForMocks(fullPath, depth + 1);
                    }
                }
            } catch (e) {}
        };
        
        scanForMocks(projectRoot);
        return mockFiles;
    }

    // ... (复用 ultra-deep-context-learning.js 中的其他方法)
    // 这里省略了大量辅助方法，实际使用时需要从原脚本复制

    /**
     * 保存结果（分批保存）
     */
    async saveResults() {
        console.log('\n💾 开始保存Foundation学习结果...\n');
        
        const knowledgeDir = this.outputDir;
        
        // 保存索引
        const indexData = {
            scope: 'foundation',
            totalProjects: this.allProjects.length,
            stats: {
                sourceFiles: this.contextGraph.sourceContexts.length,
                testFiles: this.contextGraph.testContexts.length,
                fuzzFiles: this.contextGraph.fuzzContexts.length,
                mockFiles: this.contextGraph.mockContexts.length
            },
            sourceToTestMapping: this.contextGraph.sourceToTestMapping,
            sourceToFuzzMapping: this.contextGraph.sourceToFuzzMapping,
            gnRelationships: this.contextGraph.gnRelationships
        };
        
        const indexPath = path.join(knowledgeDir, 'foundation-deep-index.json');
        fs.writeFileSync(indexPath, JSON.stringify(indexData, null, 2), 'utf-8');
        console.log(`   ✅ 已保存索引文件: foundation-deep-index.json`);
        
        // 保存详细数据（分批）
        this.saveBatches('foundation-test', this.contextGraph.testContexts, 1000);
        this.saveBatches('foundation-fuzz', this.contextGraph.fuzzContexts, 500);
        this.saveBatches('foundation-mock', this.contextGraph.mockContexts, 500);
        
        console.log(`\n💾 Foundation学习结果保存完成！\n`);
    }

    saveBatches(prefix, data, batchSize) {
        const batches = Math.ceil(data.length / batchSize);
        for (let i = 0; i < batches; i++) {
            const batch = data.slice(i * batchSize, (i + 1) * batchSize);
            const batchPath = path.join(this.outputDir, `${prefix}-${i}.json`);
            fs.writeFileSync(batchPath, JSON.stringify(batch, null, 2), 'utf-8');
            console.log(`   已保存 ${prefix} 批次 ${i + 1}: ${batch.length} 个文件`);
        }
    }

    // 辅助方法（简化版）
    findSourceFiles(dir, excludeDirs) {
        const files = [];
        const scan = (d) => {
            try {
                const entries = fs.readdirSync(d, { withFileTypes: true });
                for (const entry of entries) {
                    const fullPath = path.join(d, entry.name);
                    if (entry.isDirectory()) {
                        if (!excludeDirs.includes(entry.name) && !entry.name.startsWith('.')) {
                            scan(fullPath);
                        }
                    } else if (entry.name.endsWith('.cpp') || entry.name.endsWith('.cc')) {
                        files.push(fullPath);
                    }
                }
            } catch (e) {}
        };
        scan(dir);
        return files.slice(0, 100); // 每个项目限制100个文件
    }

    findTestFiles(dir) {
        const files = [];
        const scan = (d) => {
            try {
                const entries = fs.readdirSync(d, { withFileTypes: true });
                for (const entry of entries) {
                    const fullPath = path.join(d, entry.name);
                    if (entry.isFile() && (entry.name.endsWith('_test.cpp') || entry.name.endsWith('_unittest.cpp'))) {
                        files.push(fullPath);
                    } else if (entry.isDirectory() && !entry.name.startsWith('.')) {
                        scan(fullPath);
                    }
                }
            } catch (e) {}
        };
        scan(dir);
        return files;
    }

    findFuzzFiles(dir) {
        const files = [];
        const scan = (d) => {
            try {
                const entries = fs.readdirSync(d, { withFileTypes: true });
                for (const entry of entries) {
                    const fullPath = path.join(d, entry.name);
                    if (entry.isFile() && entry.name.endsWith('_fuzzer.cpp')) {
                        files.push(fullPath);
                    } else if (entry.isDirectory() && !entry.name.startsWith('.')) {
                        scan(fullPath);
                    }
                }
            } catch (e) {}
        };
        scan(dir);
        return files;
    }

    deepAnalyzeTestFunctions(file) {
        // 简化实现
        return { testFunction: 'HWTEST_F' };
    }

    deepAnalyzeFuzzerFunctions(file) {
        return { fuzzerFunction: 'LLVMFuzzerTestOneInput' };
    }

    deepAnalyzeMockImplementation(file) {
        return { mockClass: 'MockClass' };
    }

    establishFileMappings() {
        // 简化实现
    }

    analyzeGNDependencies() {
        // 简化实现
    }

    printSummary() {
        console.log('📊 ═══════════════════════════════════════════════════════');
        console.log('                Foundation专项学习摘要');
        console.log('═══════════════════════════════════════════════════════');
        console.log('【项目覆盖】');
        console.log(`  • 扫描项目数:          ${this.allProjects.length} 个`);
        console.log('【文件统计】');
        console.log(`  • 源文件上下文:        ${this.contextGraph.sourceContexts.length} 个`);
        console.log(`  • 测试文件上下文:      ${this.contextGraph.testContexts.length} 个`);
        console.log(`  • Fuzz文件上下文:      ${this.contextGraph.fuzzContexts.length} 个`);
        console.log(`  • Mock文件上下文:      ${this.contextGraph.mockContexts.length} 个`);
        console.log('═══════════════════════════════════════════════════════');
        console.log('🎉 Foundation核心组件学习完成！');
    }
}

// 运行
const learner = new UltraDeepFoundationLearner();
learner.run().catch(err => {
    console.error('❌ 学习过程出错:', err);
    process.exit(1);
});

